package com.tx.dishes.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.tx.dishes.pojo.Dishes;
import com.tx.dishes.service.DishesService;

@Controller
public class DishesController {

	@Autowired
	private DishesService dishesService;
	
	
	@RequestMapping("/selectAllDishes.do")
	@ResponseBody
	public List<Dishes> selectAllDishes(){
		List<Dishes> list = dishesService.selectAll();
		return list;
	}
	
	@RequestMapping("/deleteDishesByDid.do")
	@ResponseBody
	public boolean deleteDishesByDid(Dishes dishes) {
		boolean result = dishesService.deleteDishesByDid(dishes);
		return result;
	}

	@RequestMapping("/addDishes.do")
	public String addDishes(@RequestParam("img") MultipartFile f1, Dishes dishes) {
		String filename = f1.getOriginalFilename();
		File file = new File("E:\\工作软件\\apache-tomcat-8.0.33\\wtpwebapps\\ordersystem\\images\\dishes\\", filename);
		try {
			f1.transferTo(file);			//将f1的内容保存到指定位置
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		dishes.setDimage("images/dishes/"+filename);
		boolean result = dishesService.addDishes(dishes);
		System.out.println("添加菜品结果：" + result);
		return "dishesList";
	}
	
	
	@RequestMapping("/selectDishesByDid.do")
	@ResponseBody
	public Dishes selectDishesByDid(HttpSession session) {
		Dishes dishes = (Dishes) session.getAttribute("did");
		Dishes d = dishesService.selectDishesByDid(dishes);
		return d;
	}

	@RequestMapping("/updateDishesPage.do")
	public String updateDishesPage(Dishes dishes, HttpSession session) {
		session.setAttribute("did", dishes);	//保存菜品编号
		return "updateDishes";
	}
	
	@RequestMapping("/updateDishes.do")
	public String updateDishes(@RequestParam("img") MultipartFile f1, Dishes dishes) {
		String filename = f1.getOriginalFilename();
		File file = new File("E:\\工作软件\\apache-tomcat-8.0.33\\wtpwebapps\\ordersystem\\images\\dishes\\", filename);
		try {
			f1.transferTo(file);			//将f1的内容保存到指定位置
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		dishes.setDimage("images/dishes/"+filename);
		boolean result = dishesService.updateDishes(dishes);
		System.out.println("更新菜品结果：" + result);
		return "dishesList";
	}
	
	@RequestMapping("/findDishesByDid.do")
	@ResponseBody
	public Dishes findDishesByDid(Dishes d) {
		Dishes dishes = dishesService.selectDishesByDid(d);
		return dishes;
	}
	
}
